#!/usr/bin/python
#coding=UTF-8 

"""
    File:       Functional.py
    Brief:      Functional wrapper
    Author:     Xu Qiang
    Version:    1.0
    Date:       2017 - 4 - 18    create
"""


import sys
import time
import datetime
import Static
import os

from datetime import datetime
from ServiceControl import getService, ServiceState
from Log import LogD

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select

def loginWebpage( webpage = None, user = None, pwd = None ):
    '''
    this function should never raise any exception,
    '''
    
    LogD.write( sys._getframe().f_code.co_name + ' begin' )

    if webpage == None:
        webpage = Static.testEnvtConf.TargeWebPage
    if user == None:
        user = Static.testEnvtConf.LogInUserName
    if pwd == None:
        pwd = Static.testEnvtConf.LogInPassword

    browser = getService( "browser" )
    if browser == None:
        return False
    if browser.state != ServiceState.Active:
        browser.restart()

    url = ""
    try:
        url = browser.current_url
    except Exception, e:
        browser.restart()
    try:

        browser.get( webpage )

        browser.maximize_window()
        time.sleep( 1 )
#         defaultLogin( user, pwd )


    except Exception, e:
        from Log import LogW
        LogW.write( "loginWebpage cause Exception %s" % str( e ) )
        return False
    
    return True

def wait_time( second ):
    time.sleep(second)

def defaultLogin( user, pwd ):
    browser = getService( "browser" )
    browser.find_element("id","inputUserName").clear()
    browser.find_element("id","inputUserName").send_keys(user)
    browser.find_element("id","inputPassword").clear()
    browser.find_element("id","inputPassword").send_keys (pwd)
    browser.find_element("id","loginBtn").click()

def translateFileName( filename ):
    if not os.path.exists( Static.PICoutputPath ):
        os.makedirs( Static.PICoutputPath)
    if "\\" in filename or "/" in filename:
        return filename
    else:
        return Static.PICoutputPath + filename
    
def capturePIC(filename):  
    timestring = GetTimeString()
    timestring = timestring.replace(":","-")
    timestring = timestring[0:19]
    fileName = timestring + "_"+ str(filename)   
    getService( "browser" ).get_screenshot_as_file( translateFileName( fileName ) )
    
def GetTimeString():
    timeNow = datetime.now()
    timestring = timeNow.strftime("%Y-%m-%d:%H:%M:%S.")
    millisecond = str(timeNow.microsecond/1000)
    millisecondstring = '0'*(3-len(millisecond)) + millisecond
    timestring = timestring + millisecondstring
    return timestring

def MoveToElement(element):  
    ActionChains( getService( "browser" )).move_to_element(element).perform()
